package com.tanhua.server.service;

import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TodayBestService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private UserLocationApi userLocationApi;

    /**
     * 查询今日佳人
     */
    public ResponseEntity queryTodayBest() {
        //1、获取当前登录用户的用户id
        Long userId = UserHolder.getUserId();
        //2、调用api查询数据
        RecommendUser user = recommendUserApi.queryWithMaxScore(userId);
        if(user == null) {
            user = new RecommendUser();  //当推荐用户不存在时，默认值
            user.setUserId(2l);
            user.setScore(95d);
        }
        //3、根据查询的推荐用户，查询用户信息
        UserInfo info = userInfoApi.findById(user.getUserId());
        //4、构造vo对象
        TodayBest best = new TodayBest();
        BeanUtils.copyProperties(info, best);
        best.setFateValue(user.getScore().longValue());
        if(!StringUtils.isEmpty(info.getTags())) {
            best.setTags(info.getTags().split(","));
        }
        //5、返回值
        return ResponseEntity.ok(best);
    }

    /**
     * 分页查询首页推荐用户列表
     *  Map map
     *      page，pagesize，gender
     */
    public ResponseEntity queryRecommendUserList(RecommendUserQueryParam param) {
        //1、获取当前登录用户的id
        Long userId = UserHolder.getUserId();
        //2、调用API查询分页数据
        int page = param.getPage();
        int pagesize = param.getPagesize();
        PageResult result = recommendUserApi.queryRecommendUserList(page, pagesize, userId);
        //3、获取分页数据列表  List<RecommendUser> list
        List<RecommendUser> items = (List<RecommendUser>) result.getItems();
        //如果查询的推荐列表为null，构造默认的推荐数据
        if(items == null || items.size() <=0) {
            items = defaultRecommend();
        }
        //4、一个RecommendUser对象，转化为一个TodayBest
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            //a.根据RecommendUser中的userId查询用户详情userInfo
            UserInfo info = userInfoApi.findById(item.getUserId());
            //b.构建TodayBest
            TodayBest best = new TodayBest();
            //c.将userInfo中的属性赋值到TodayBest中
            BeanUtils.copyProperties(info, best);
            best.setFateValue(item.getScore().longValue());
            if(!StringUtils.isEmpty(info.getTags())) {
                best.setTags(info.getTags().split(","));
            }
            //d.存入list集合
            list.add(best);
        }
        //5、构造返回值
        result.setItems(list);
        return ResponseEntity.ok(result);
    }

    //构造默认数据
    private List<RecommendUser> defaultRecommend() {
        String ids = "1,2,3,4,5,6,7,8,9,10";
        List<RecommendUser> records = new ArrayList<>();
        for (String id : ids.split(",")) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(Long.valueOf(id));
            recommendUser.setScore(RandomUtils.nextDouble(70, 98));
            records.add(recommendUser);
        }
        return records;
    }

    //查询佳人详情
    public ResponseEntity personalInfo(Long userId) {
        //1、查询用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2、根据当前用户id，和感兴趣的用户id查询缘分值
        Long fateValue = recommendUserApi.queryScore(UserHolder.getUserId(),userId);
        //3、构造返回值 TodayBest
        TodayBest best = new TodayBest();
        BeanUtils.copyProperties(userInfo, best);
        best.setTags(userInfo.getTags().split(","));
        best.setFateValue(fateValue);
        return ResponseEntity.ok(best);
    }

    //查看陌生人问题
    public ResponseEntity queryQuestions(Long userId) {
        //1、根据id查询Question对象
        Question question = questionApi.findByUserId(userId);
        //2、构造返回值
        String txt = question==null?"黑马36怎么样？":question.getTxt();
        return ResponseEntity.ok(txt);
    }

    /**
     * 搜索附近的人
     */
    public ResponseEntity searchNear(String gender, String distance) {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、调用API根据用户id，距离查询当前用户附件的人 List<UserLocationVo>
        List<UserLocationVo> locations = userLocationApi.searchNear(userId,Long.valueOf(distance));
        //3、循环附近的人所有数据
        List<NearUserVo> users = new ArrayList<>();
        for (UserLocationVo location : locations) {
            //4、调用UserInfoApi查询用户数据，构造NearUserVo对象
            UserInfo info = userInfoApi.findById(location.getUserId());
            if(info.getId() == userId) {  //排除自己
                continue;
            }
            if(gender !=null && !info.getGender().equals(gender)) { //排除性别不符合
                continue;
            }
            NearUserVo vo = new NearUserVo();
            vo.setUserId(info.getId());
            vo.setAvatar(info.getAvatar());
            vo.setNickname(info.getNickname());
            users.add(vo);
        }
        return ResponseEntity.ok(users);
    }
}
